<!--
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-02 15:03:05
 * @LastEditors  : cxguo
 * @LastEditTime : 2019-12-26 17:05:59
 -->
<template>
  <div>
    <el-container>
      <el-aside width="150px" :class="aside">
        <cate-tree @node-click="handleNodeClick" />
      </el-aside>
      <el-main :style="{marginLeft:`${mainLeft}`}">
        <div>
          <el-input
            v-model="searchData.keywords"
            size="small"
            style="width: 360px"
            placeholder="按商品编号, 商品名称, 规格型号等查询."
            @keydown.enter.native="btnSearch"
          >
            <el-button slot="append" icon="el-icon-search" type="primary" :loading="btnLoading.search" @click="btnSearch()" />
          </el-input>
          <el-button
            v-if="oper === 'list'"
            class="fr"
            size="small"
            type="success"
            @click="handleAddProduct"
          >
            添 加
          </el-button>
          <el-button
            v-if="oper === 'select'"
            class="fr"
            size="small"
            type="success"
            @click="btnSelectSure"
          >
            确定采购
          </el-button>
        </div>
        <div class="table-container">
          <vxe-grid
            ref="table"
            class="grid"
            border
            size="mini"
            resizable
            highlight-hover-row
            show-footer
            :columns="columnsData"
            :data="tableData.goods"
          />
        </div>
        <div class="batch-operate-container">
          <el-select
            v-model="operateType"
            size="small"
            placeholder="批量操作"
          >
            <el-option
              v-for="item in operates"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button
            style="margin-left: 20px"
            class="search-button"
            type="primary"
            size="small"
            @click="handleBatchOperate()"
          >
            确定
          </el-button>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            layout="total, sizes,prev, pager, next,jumper"
            :page-size="pageInfo.rows"
            :page-sizes="[20,30,40]"
            :current-page.sync="pageInfo.page"
            :total="pageInfo.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import {
  delData,
  updateDeleteStatus,
  updateNewStatus,
  updateRecommendStatus,
  updatePublishStatus
} from '@/api/goods/goods.js'
import { listData } from '@/api/goods/goods-sku.js'
import { oftenuse, goods as goodsMix } from '@/libs/mixins'
import cateTree from '@/views/goods/category'
import { srcoll } from './mixins'

const defaultsearchData = {
}
export default {
  name: 'GoodsList',
  components: { cateTree },
  filters: {
    verifyStatusFilter(value) {
      if (value === 1) {
        return '审核通过'
      } else {
        return '未审核'
      }
    }
  },
  mixins: [oftenuse, srcoll, goodsMix],
  props: {
    oper: {
      type: String,
      default: 'list'
    }
  },
  data() {
    return {
      columnsData: [
        { title: '操作', width: 160,
          slots: {
            default: ({ row, seq }) => {
              const addButton = {
                props: {
                  size: 'mini', type: 'danger'
                },
                on: {
                  click: (params) => { this.handleDelete(params, row) }
                }
              }
              const viewButton = {
                props: {
                  size: 'mini', type: 'primary'
                },
                on: {
                  click: (params) => { this.handleShowProduct(params, row) }
                }
              }
              return [
                <div>
                  <el-button {...addButton}>删 除</el-button>
                  <el-button {...viewButton}>查 看</el-button>
                </div>
              ]
            }
          }
        },
        { field: 'code', title: '商品编号', showOverflow: true, width: 120 },
        { field: 'name', title: '商品名称/规格', showOverflow: true, width: 200 },
        { field: 'catName', title: '类别', width: 100 },
        { field: 'unitbase', title: '基本单位', width: 100,
          slots: {
            default: ({ row, seq }) => {
              const unitbaseStr = row['unitbase']
              const unitbase = JSON.parse(unitbaseStr)
              return [<span>{unitbase.label}</span>]
            }
          }
        },
        { field: 'price', title: '零售价', showOverflow: true, width: 100,
          slots: {
            default: ({ row, seq }) => {
              const priceStr = row['price']
              const price = JSON.parse(priceStr)
              const value = price ? price['零售价'] : '0'
              return [<span>{value}</span>]
            }
          }
        }
      ],
      operates: [
        {
          label: '转移到分类',
          value: 'transferCategory'
        },
        {
          label: '移入回收站',
          value: 'recycle'
        }
      ],
      operateType: null,
      searchData: Object.assign({}, defaultsearchData),
      selectProductCateValue: null,
      multipleSelection: [],
      productCateOptions: []
    }
  },
  watch: {
    selectProductCateValue: function(newValue) {
      if (newValue != null && newValue.length === 2) {
        this.searchData.productCategoryId = newValue[1]
      } else {
        this.searchData.productCategoryId = null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    btnSearch() {
      this.pageInfo.page = 1
      this.setBtnLoading('search', true)
      this.getList().then((res) => {
        this.setBtnLoading('search', false)
      }).catch(err => {
        console.log(err)
        this.setBtnLoading('search', false)
      })
    },
    btnSelectSure() {
      this.$bus.$emit('on-goods-select-sure', this.getHasNumGoodsData(this.list))
    },
    /**
     * 获取有数量的商品数据
     */
    getHasNumGoodsData(tableData) {
      return tableData.filter(item => { return item.num > 0 })
    },
    // api
    getList(params = { data: this.searchData, pageInfo: this.pageInfo }) {
      this.setTableLoading('goods', true)
      return new Promise((resolve, reject) => {
        listData(params).then(res => {
          if (res.data.flag) {
            this.setTableLoading('goods', false)
            this.setTableData('goods', res.data.data)
            this.pageInfo = res.data.pageInfo
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    delData(params) {
      delData(params).then(res => {
        this.$message[res.data.flag ? 'info' : 'error'](res.data.message)
        if (res.data.flag) this.getList()
      })
    },
    // on
    handleNodeClick(data) {
      this.getList({
        data: { typeId: data.id },
        pageInfo: this.pageInfo
      })
    },
    handleAddProduct() {
      this.jump2goodsDetail()
    },
    handleBatchOperate() {
      if (this.operateType == null) {
        this.$message({
          message: '请选择操作类型',
          type: 'warning',
          duration: 1000
        })
        return
      }
      if (this.multipleSelection == null || this.multipleSelection.length < 1) {
        this.$message({
          message: '请选择要操作的商品',
          type: 'warning',
          duration: 1000
        })
        return
      }
      this.$confirm('是否要进行该批量操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id)
        }
        switch (this.operateType) {
          case this.operates[0].value:
            this.updatePublishStatus(1, ids)
            break
          case this.operates[1].value:
            this.updatePublishStatus(0, ids)
            break
          case this.operates[2].value:
            this.updateRecommendStatus(1, ids)
            break
          case this.operates[3].value:
            this.updateRecommendStatus(0, ids)
            break
          case this.operates[4].value:
            this.updateNewStatus(1, ids)
            break
          case this.operates[5].value:
            this.updateNewStatus(0, ids)
            break
          case this.operates[6].value:
            break
          case this.operates[7].value:
            this.updateDeleteStatus(1, ids)
            break
          default:
            break
        }
        this.getList()
      })
    },
    handleSizeChange(val) {
      this.pageInfo.page = 1
      this.pageInfo.rows = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.pageInfo.page = val
      this.getList()
    },
    handleSelectionChange(dataList) {
      this.multipleSelection = dataList
    },
    handleDelete(index, row) {
      this.$confirm('是否要进行删除操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delData(row.id)
      })
    },
    handleShowProduct(index, row) {
      this.jump2goodsDetail(row.id)
    },
    updatePublishStatus(publishStatus, ids) {
      const params = new URLSearchParams()
      params.append('ids', ids)
      params.append('publishStatus', publishStatus)
      updatePublishStatus(params).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        })
      })
    },
    updateNewStatus(newStatus, ids) {
      const params = new URLSearchParams()
      params.append('ids', ids)
      params.append('newStatus', newStatus)
      updateNewStatus(params).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        })
      })
    },
    updateRecommendStatus(recommendStatus, ids) {
      const params = new URLSearchParams()
      params.append('ids', ids)
      params.append('recommendStatus', recommendStatus)
      updateRecommendStatus(params).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        })
      })
    },
    updateDeleteStatus(deleteStatus, ids) {
      const params = new URLSearchParams()
      params.append('ids', ids)
      params.append('deleteStatus', deleteStatus)
      updateDeleteStatus(params).then(response => {
        this.$message({
          message: '删除成功',
          type: 'success',
          duration: 1000
        })
      })
      this.getList()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .aside {
    .el-tree {
      // background: #f1f1f7;
      color:#8b8ba2
    }
    // background: #f1f1f7;
    border-right: #ebeef5 solid 1px;
  }
  .fixed {
    position: fixed; top:0;
  }
</style>
